var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var router = express.Router();
//连接MySQL数据库
var client = mysql.createConnection({
    host: 'localhost',
    port:"3306",
    user: 'root',
    password: '123456',
    database: 'akb48'
});
//判断数据库是否连接成功
client.connect(function(err){
    if(err){
         console.log('[query] - :'+err);
         return;
    }
    console.log('[connection connect]  MySQL数据库连接成功!');
});



//显示登录列表
router.get('/', function (request, response) {
    response.render('login/login.ejs');
});

//添加登录处理逻辑
router.post('/', function (request, response) {
    console.log(request.body);
    
      //执行SQL语句
      client.query('select * from user where username = ? and password = ?', 
        [request.body.username,request.body.password],   function (err, results) {
            //响应信息
        if(results.length>0){
            console.log(results)
            response.render('home',{
                data: results[0]
            });
        }else{
            client.query('insert into user (username, password,nikename) VALUES (?,?,?)', [
                request.body.username, request.body.password,request.body.username
            ], function () {
                //响应信息
                response.render('home',{
                    data: {
                        nikename: "新注册用户"+request.body.username
                    }
                });
            });
        }
   });


});
module.exports = router;